package com.sykj.springboot.common.Exception;

import com.sykj.springboot.common.entity.DataResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

//全局异常处理 只需要在Controller上把异常直接抛出即可
@ControllerAdvice(annotations = {RestController.class})
public class ExceptionHandlerAdvice {

    //兜底的所有异常处理
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public DataResponse exceptionHandler(HttpServletRequest request,Exception e){
        DataResponse response = new DataResponse();
        response.setMsg(DataResponse.MSG_F);
        response.setStatus(DataResponse.STATUS_F);
        return response;
    }

    //自定义异常 BussinessException的处理
    @ResponseBody
    @ExceptionHandler(BussinessException.class)
    public DataResponse bussinessExceptionHandler(HttpServletRequest request,BussinessException e){
        DataResponse response = new DataResponse();
        response.setMsg(e.getMessage());
        response.setStatus(DataResponse.STATUS_F);
        return response;
    }

    //自定义异常 TimeOutException的处理
    @ResponseBody
    @ExceptionHandler(TimeOutException.class)
    public DataResponse timeOutExceptionHandler(HttpServletRequest request,TimeOutException e){
        DataResponse response = new DataResponse();
        response.setMsg("登录超时");
        response.setStatus(DataResponse.STATUS_T);
        return response;
    }
}
